﻿using AutoMapper;
using FastJSON;
using HuiJiYunGo.EF;
using HuiJiYunGo.Tools;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace HuiJiYunGO.Controllers
{
    public class MobileController : BaseController
    {
        // GET: Mobile
        public ActionResult Index(long page = 1)
        {

            HuiJiDBContainer db = new HuiJiDBContainer();
            if (Request.UrlReferrer == null)
            {
                //算一次访问
                AddOpRecord("访问人次", "访问人次", 1);
                if (IsWeiXin())
                {
                    AddOpRecord("微信", "访问来源", 1);
                }
                else
                {
                    AddOpRecord("Mobile", "访问来源", 1);
                }
            }
           
            ViewBag.IsWeiXin = IsWeiXin();
            var AppBar = GetAppBarList().Where(m => m.Code == "MobileIndex").FirstOrDefault();
            var MaterialId = AppBar.Material_ID;
            ViewBag.Ad_img = AppBar.Ad_Img;
            ViewBag.AppBarCode = "MobileIndex";
           
            var materia = db.Material.Where(m => m.MaterialId == MaterialId).First();
            ViewBag.Mid = materia.Id;

            //ViewBag.Page = page;
            //ITopClient client = new DefaultTopClient(url, appkey, secret);
            //TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
            //req.PageSize = 40L;
            //req.AdzoneId = adzoneId;
            //req.PageNo = page;
            //req.MaterialId = MaterialId;
            //req.DeviceValue = null;
            //req.DeviceEncrypt = null;
            //req.DeviceType = null;
            //req.ContentId = null;
            //req.ContentSource = null;
            //req.ItemId = null; ;
            //req.FavoritesId = "";
            //TbkDgOptimusMaterialResponse rsp = client.Execute(req);
            ////req.PageSize = 8L;
            ////req.PageNo = 1L;
            ////req.MaterialId = 3756L;
            ////TbkDgOptimusMaterialResponse rsp2 = client.Execute(req);
            ////req.PageSize = 7L;
            ////req.PageNo = 1L;
            ////req.MaterialId = 4094L;
            ////TbkDgOptimusMaterialResponse rsp3 = client.Execute(req);
            //ViewBag.Limit = req.PageSize;
            //ViewBag.TotalCount = "500";
            //ViewBag.MaterialList = rsp.ResultList;
            //ViewBag.HaoQuan = rsp2.ResultList;
            //ViewBag.TeHui = rsp3.ResultList;

            ViewBag.SlideShowList = GetSlideShowList().Where(m => m.ShowPhone == true).ToList();
            return View();
        }

        [HttpGet]
        public ActionResult Search(string Key, string Mid, string Cid)
        {
            ViewBag.Key = Key;
            ViewBag.Mid = Mid;
            ViewBag.Cid = Cid;
            return View();
        }

        [HttpPost]
        public ActionResult AjaxSearch(int page = 1, string Key = "", long? Mid = 2836, int Page = 1, long? ep = null, long? sp = null, string cat = "", string sort = "total_sales_des")
        {

            ViewBag.Key = Key;
            //聚划算 接口 
            //ITopClient client = new DefaultTopClient(url, appkey, secret);
            //JuItemsSearchRequest req = new JuItemsSearchRequest();
            //JuItemsSearchRequest.TopItemQueryDomain obj1 = new JuItemsSearchRequest.TopItemQueryDomain();
            //obj1.CurrentPage = page;
            //obj1.PageSize = 40L;
            //obj1.Pid = Pid;
            //obj1.Postage = true;
            //obj1.Status = 1L;
            //obj1.TaobaoCategoryId = Cid;
            //obj1.Word = Key;
            //req.ParamTopItemQuery_ = obj1;
            //JuItemsSearchResponse rsp = client.Execute(req);
            //Console.WriteLine(rsp.Body);
            //ViewBag.JuItemsSearch = rsp.Result;//JuItemsSearchResponse PaginationResultDomain
            ITopClient client = new DefaultTopClient(url, appkey, secret);
            TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
            req.StartDsr = null;
            req.PageSize = 20;
            req.PageNo = Page;
            req.Platform = 1L;
            req.EndTkRate = null;
            req.StartTkRate = null;
            req.EndPrice = ep;
            req.StartPrice = sp;
            req.IsOverseas = false;
            req.IsTmall = true;
            req.Sort = sort;
            req.Itemloc = null;
            req.Cat = cat;
            req.Q = Key;
            req.MaterialId = Mid;//不传时默认物料id=2836；如果直接对消费者投放，可使用官方个性化算法优化的搜索物料id=17004
            req.HasCoupon = true;
            req.Ip = null;
            req.AdzoneId = adzoneId;
            req.NeedFreeShipment = true;
            req.NeedPrepay = true;
            req.IncludePayRate30 = true;
            req.IncludeGoodRate = true;
            req.IncludeRfdRate = true;
            req.NpxLevel = 1L;//不限
            req.EndKaTkRate = null;
            req.StartKaTkRate = null;
            req.DeviceEncrypt = null;
            req.DeviceValue = null;
            req.DeviceType = null;
            req.LockRateEndTime = null;
            req.LockRateStartTime = null;
            req.Longitude = null;
            req.Latitude = null;
            req.CityCode = null;
            req.SellerIds = null;
            req.SpecialId = null;
            req.RelationId = null;
            TbkDgMaterialOptionalResponse rsp = client.Execute(req);
            if (rsp.IsError)
            {
                //失败就在来一次
                rsp = client.Execute(req);
            }

            foreach (var item in rsp.ResultList)
            {
                CacheHelper.SetCache("tbk_ss_" + item.ItemId, item, DateTime.Now.AddMinutes(10), TimeSpan.Zero);
            }

            //ViewBag.TotalResults = rsp.TotalResults;
            //ViewBag.ResultList = rsp.ResultList;

            return Json(new { rsp.ResultList, rsp.TotalResults }, JsonRequestBehavior.DenyGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult MeiShi(int page = 1)
        {
            var MaterialId = GetAppBarList().Where(m => m.Code == "MobileIndex").FirstOrDefault().Material_ID;
            ViewBag.AppBarCode = "Index";
            ViewBag.Page = page;
            ITopClient client = new DefaultTopClient(url, appkey, secret);
            TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
            req.PageSize = 40L;
            req.AdzoneId = adzoneId;
            req.PageNo = page;
            req.MaterialId = 27451;
            req.DeviceValue = null;
            req.DeviceEncrypt = null;
            req.DeviceType = null;
            req.ContentId = null;
            req.ContentSource = null;
            req.ItemId = null; ;
            req.FavoritesId = "";
            TbkDgOptimusMaterialResponse rsp = client.Execute(req);
            //req.PageSize = 8L;
            //req.PageNo = 1L;
            //req.MaterialId = 3756L;
            //TbkDgOptimusMaterialResponse rsp2 = client.Execute(req);
            //req.PageSize = 7L;
            //req.PageNo = 1L;
            //req.MaterialId = 4094L;
            //TbkDgOptimusMaterialResponse rsp3 = client.Execute(req);
            ViewBag.Limit = req.PageSize;
            ViewBag.TotalCount = "500";
            ViewBag.MaterialList = rsp.ResultList;

            return View();
        }

        public ActionResult Category(int id = -1)
        {
            ViewBag.AppBarCode = "MobileCategory";

            ViewBag.CategoryList = GetCategoryList();
            if (id == -1)
            {

                ViewBag.Id = GetCategoryList().Where(m => m.Pid == 0 && m.ShowPhone == true).First().Id;
            }
            else
            {
                ViewBag.Id = id;
            }
            return View();
        }


        public ActionResult Gather()
        {
            ViewBag.AppBarCode = "MobileGather";
            HuiJiDBContainer db = new HuiJiDBContainer();
            ViewBag.ShowSpecial = db.AppBar.Where(m => m.ShowSpecial == true).ToList();
            return View();
        }


        public ActionResult MaterialList(string v2, string v3 = "", int abid = -1)
        {
            HuiJiDBContainer db = new HuiJiDBContainer();
            var appbar = db.AppBar.FirstOrDefault(m => m.Id == abid);
            if (appbar != null)
            {
                ViewBag.Ad_Img = appbar.Ad_Img;

            }
            if (!string.IsNullOrWhiteSpace(v2))
            {
                ViewBag.MaterialName = v2;
                //HuiJiDBContainer db = new HuiJiDBContainer();
                var MaterialList = db.Material.Where(m => m.CategoryV2 == appbar.Mv2 && m.IsEnable == true && m.ShowPhone == true).ToList();
                ViewBag.MaterialList = MaterialList;
            }
            if (!string.IsNullOrWhiteSpace(v3))
            {
                ViewBag.MaterialName = v3;
                //HuiJiDBContainer db = new HuiJiDBContainer();
                var MaterialList = db.Material.Where(m => m.CategoryV3 == appbar.Mv3 && m.IsEnable == true && m.ShowPhone == true).ToList();
                ViewBag.MaterialList = MaterialList;
            }

            return View();
        }
        /// <summary>
        /// 搭配 MaterialList 用
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AjaxMaterialList(int id, int page = 1)
        {

            HuiJiDBContainer db = new HuiJiDBContainer();
            var materia = db.Material.Where(m => m.Id == id).First();
            //ITopClient client = new DefaultTopClient(url, appkey, secret);
            //TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
            //req.PageSize = 20L;
            //req.AdzoneId = adzoneId;
            //req.PageNo = page;
            //req.MaterialId = materia.MaterialId;
            //TbkDgOptimusMaterialResponse rsp = client.Execute(req);
            var TotalCount = db.MaterialGoods.Count(m => m.Mid == materia.Id);
            var ResultList = db.MaterialGoods.Where(m => m.Mid == materia.Id).OrderByDescending(m => new { m.CreateTime, m.Volume }).Skip(20 * (page - 1)).Take(20).ToList();
            return Json(new { ResultList, TotalCount }, JsonRequestBehavior.DenyGet);
            //Console.WriteLine(rsp.Body);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="itemid"></param>
        /// <param name="xs">推荐</param>
        /// <param name="ss">搜索</param>
        /// <returns></returns>
        public ActionResult GoodsDetails(string itemid, bool xs = false, bool ss = false, bool qg = false)
        {
            ViewBag.IsToTKLinkOk = true;
            ViewBag.IsWeiXin = IsWeiXin() ? "1" : "0";
            HuiJiDBContainer db = new HuiJiDBContainer();
            //ITopClient client = new DefaultTopClient(url, appkey, secret);
            //TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
            //req.NumIids = itemid;
            //req.Platform = 2L;
            //req.Ip = Request.UserHostAddress;
            //TbkItemInfoGetResponse rsp = client.Execute(req);
            //ViewBag.ItemDetail = rsp.Results.First();
            if (xs)
            {
                var itemObject = CacheHelper.GetCache("tbk_xstj_" + itemid);
                if (itemObject == null)
                {
                    return RedirectToAction("Index", "Mobile");
                }
                TbkDgOptimusMaterialResponse.MapDataDomain item = itemObject as TbkDgOptimusMaterialResponse.MapDataDomain;
                MaterialGoods mg = new MaterialGoods()
                {
                    ItemId = item.ItemId.ToString(),
                    Title = item.Title,
                    UserType = (int)item.UserType,
                    SmallImages = JSON.ToJSON(item.SmallImages),
                    CouponAmount = (int)item.CouponAmount,
                    ZkFinalPrice = decimal.Parse(item.ZkFinalPrice),
                    Volume = (int)item.Volume,
                    ItemDescription = item.ItemDescription,
                    ReservePrice = item.ReservePrice,
                    PictUrl = item.PictUrl,
                    ShortTitle = item.ShortTitle,
                    CouponShareUrl = item.CouponShareUrl
                };
                ViewBag.mgoods = mg;
            }
            else if (ss)
            {
                var itemObject = CacheHelper.GetCache("tbk_ss_" + itemid);
                if (itemObject == null)
                {
                    return RedirectToAction("Index", "Mobile");
                }
                TbkDgMaterialOptionalResponse.MapDataDomain item = itemObject as TbkDgMaterialOptionalResponse.MapDataDomain;
                MaterialGoods mg = new MaterialGoods()
                {
                    ItemId = item.ItemId.ToString(),
                    Title = item.Title,
                    UserType = (int)item.UserType,
                    SmallImages = JSON.ToJSON(item.SmallImages),
                    CouponAmount = int.Parse(item.CouponAmount),
                    ZkFinalPrice = decimal.Parse(item.ZkFinalPrice),
                    Volume = (int)item.Volume,
                    ItemDescription = item.ItemDescription,
                    ReservePrice = item.ReservePrice,
                    PictUrl = item.PictUrl,
                    ShortTitle = item.ShortTitle,
                    CouponShareUrl = item.CouponShareUrl
                };
                ViewBag.mgoods = mg;
            }
            else if (qg)
            {
                ViewBag.Type = "TQG";
                var rush = db.Rush.FirstOrDefault(m => m.ItemID == itemid);

                ITopClient clientqg = new DefaultTopClient(url, appkey, secret);
                TbkItemInfoGetRequest reqqg = new TbkItemInfoGetRequest();
                reqqg.NumIids = itemid;
                reqqg.Platform = 2L;
                //reqqg.Ip = "11.22.33.43";

                TbkItemInfoGetResponse rspqg = clientqg.Execute(reqqg);
                if (rspqg.Results.Count != 0)
                {

                    MaterialGoods mg = new MaterialGoods()
                    {
                        ItemId = rspqg.Results[0].NumIid.ToString(),
                        Title = rush.Title,
                        UserType = (int)rspqg.Results[0].UserType,
                        SmallImages = JSON.ToJSON(rspqg.Results[0].SmallImages),
                        CouponAmount = 0,// int.Parse(rspqg.Results[0]),
                        ZkFinalPrice = decimal.Parse(rush.ZkFinalPrice),
                        Volume = (int)rspqg.Results[0].Volume,
                        //ItemDescription = rspqg.Results[0].ItemDescription,
                        ReservePrice = rush.ReservePrice,
                        PictUrl = rush.PicUrl,
                        ShortTitle = rspqg.Results[0].Title,
                        CouponShareUrl = rush.ClickUrl,
                        ClickUrl = rush.ClickUrl
                    };
                    ViewBag.mgoods = mg;
                    ViewBag.IsToTKLinkOk = IsToTKLinkOk(mg.ClickUrl);
                }
                else
                {
                    MaterialGoods mg = new MaterialGoods()
                    {
                        ItemId = rush.ItemID,
                        Title = rush.Title,
                        UserType = null,
                        SmallImages = "",// JSON.ToJSON(rspqg.Results[0].SmallImages),
                        CouponAmount = 0,// int.Parse(rspqg.Results[0]),
                        ZkFinalPrice = decimal.Parse(rush.ZkFinalPrice),
                        Volume = rush.SoldNum,
                        //ItemDescription = rspqg.Results[0].ItemDescription,
                        ReservePrice = rush.ReservePrice,
                        PictUrl = rush.PicUrl,
                        ShortTitle = "", //rspqg.Results[0].Title,
                        CouponShareUrl = rush.ClickUrl,
                        ClickUrl = rush.ClickUrl
                    };
                    ViewBag.mgoods = mg;
                    ViewBag.IsToTKLinkOk = IsToTKLinkOk(mg.ClickUrl);
                }



            }
            else
            {

                var mgoods = db.MaterialGoods.FirstOrDefault(m => m.ItemId == itemid);
                ViewBag.mgoods = mgoods;
            }


            //相似推荐
            ITopClient client = new DefaultTopClient(url, appkey, secret);
            TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
            req.PageSize = 10L;
            req.AdzoneId = adzoneId;
            req.PageNo = 1L;
            req.MaterialId = 13256;
            req.ItemId = long.Parse(itemid);

            TbkDgOptimusMaterialResponse rsp = client.Execute(req);

            //Console.WriteLine(rsp.Body);
            //将相似推荐加入缓存 缓存 10 分钟
            foreach (var item in rsp.ResultList)
            {
                CacheHelper.SetCache("tbk_xstj_" + item.ItemId, item, DateTime.Now.AddMinutes(10), TimeSpan.Zero);
            }

            ViewBag.SimilarRecommend = rsp.ResultList;

            return View();
        }

        [HttpPost]
        public ActionResult Tkl(string url, string title)
        {
            //"https:" +
            if (!url.Contains("https:"))
            {
                url = "https:" + url;
            }
            ITopClient client = new DefaultTopClient(base.url, appkey, secret);
            TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
            req.UserId = "1";
            req.Logo = "https://uland.taobao.com/";
            req.Text = title;
            req.Url = url;
            TbkTpwdCreateResponse response = client.Execute(req);
            return Json(response, JsonRequestBehavior.DenyGet);
        }


        public ActionResult TaoQiangGou()
        {

            DateTime now = DateTime.Now;
            DateTime todayStart = new DateTime(now.Year, now.Month, now.Day);//今日开始
            DateTime tomorrowEnd = todayStart.AddDays(1);//明日结束

            HuiJiDBContainer db = new HuiJiDBContainer();
            //var RushList = db.Rush.Where(m => m.StartTime >= todayStart && m.StartTime <= tomorrowEnd).ToList();//拿到所有抢购信息

            List<DateTime?> TimeGroup = db.Rush.Where(m => m.StartTime >= todayStart && m.StartTime <= tomorrowEnd).GroupBy(m => m.StartTime).Select(m => m.Key).ToList();

            List<RushViewModel> RvwList = new List<RushViewModel>();
            for (int i = 0; i < TimeGroup.Count; i++)
            {
                RushViewModel rvw = new RushViewModel();
                //rvw.Rushs = RushList.Where(m => m.StartTime == TimeGroup[i]).ToList();
                rvw.StartTime = TimeGroup[i].Value;
                rvw.TimeStr = (TimeGroup[i].Value.Date == DateTime.Now.Date ? "" : "") + TimeGroup[i].Value.ToString("t");
                if (i != TimeGroup.Count - 1 && DateTime.Now > TimeGroup[i] && DateTime.Now < TimeGroup[i + 1])
                    rvw.IsCurrent = true;
                RvwList.Add(rvw);
            }
            ViewBag.RushData = RvwList;
            return View();
        }
        [HttpPost]
        public ActionResult AjaxTaoQiangGou(DateTime time, int page)
        {
            HuiJiDBContainer db = new HuiJiDBContainer();
            var TotalCount = db.Rush.Count(m => m.StartTime == time);
            var ResultList = db.Rush.Where(m => m.StartTime == time).OrderByDescending(m => m.SoldNum).Skip(20 * (page - 1)).Take(20).ToList();
            return Json(new { ResultList, TotalCount }, JsonRequestBehavior.DenyGet);
        }


        public ActionResult NPN()
        {
            ViewBag.AppBarCode = "MobileNPN";
            return View();
        }
        [HttpPost]
        public ActionResult AjaxNPN(int page)
        {
            HuiJiDBContainer db = new HuiJiDBContainer();

            var TotalCount = db.MaterialGoods.Count(m => (m.ZkFinalPrice - m.CouponAmount) < 11);

            var ResultList = db.MaterialGoods.Where(m => (m.ZkFinalPrice - m.CouponAmount) < 11).OrderByDescending(m => new { m.CreateTime, m.Volume }).Skip(20 * (page - 1)).Take(20).ToList();
            return Json(new { TotalCount, ResultList }, JsonRequestBehavior.DenyGet);
        }


        public ActionResult SlideDetails(int id)
        {

            HuiJiDBContainer db = new HuiJiDBContainer();
            var SlideShow = db.SlideShow.FirstOrDefault(m => m.Id == id);
            var url = SlideShow.Link_to;
            if (!url.Contains("https:"))
            {
                url = "https:" + url;
            }
            ITopClient client = new DefaultTopClient(base.url, appkey, secret);
            TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
            req.UserId = "1";
            req.Logo = "https://uland.taobao.com/";
            req.Text = SlideShow.Name;
            req.Url = url;
            TbkTpwdCreateResponse response = client.Execute(req);

            ViewBag.TKL = response.Data.Model;
            ViewBag.BGM = SlideShow.Img_Src;
            ViewBag.Name = SlideShow.Name;
            return View();
        }
    }
}